// 需要登录才能访问的页面路径列表
const authPages = [
  '/pages/index/index',
  '/pages/attack/index',
  // 添加其他需要登录的页面路径
];

// 全局状态
const globalState = {
  timeSettings: {
    startTime: '10:00',
    stopTime: '11:40'
  }
};

// Token 相关操作
const TOKEN_KEY = 'auth_token';

// 添加防抖处理
let lastNavigateTime = 0;
const NAVIGATE_DEBOUNCE = 1000; // 1秒内不重复跳转

// 设置 token
const setToken = (token) => {
  try {
    uni.setStorageSync(TOKEN_KEY, token);
    uni.setStorageSync('isLoggedIn', true);
  } catch (e) {
    console.error('保存 token 失败:', e);
  }
};

// 获取 token
const getToken = () => {
  try {
    return uni.getStorageSync(TOKEN_KEY);
  } catch (e) {
    console.error('获取 token 失败:', e);
    return null;
  }
};

// 清除 token
const clearToken = () => {
  try {
    uni.removeStorageSync(TOKEN_KEY);
    uni.removeStorageSync('isLoggedIn');
  } catch (e) {
    console.error('清除 token 失败:', e);
  }
};

// 检查是否已登录
const isLoggedIn = () => {
  const token = getToken();
  return !!token;
};

// 更新全局状态
const updateGlobalState = (key, value) => {
  try {
    // 对于运行状态，直接更新存储并发送事件
    if (key === 'isRunning') {
      if (value) {
        uni.setStorageSync('plunder_running', true);
      } else {
        uni.removeStorageSync('plunder_running');
      }
      // 发送状态更新事件
      uni.$emit('globalStateChange', { key, value });
      uni.$emit('running-state-changed', { isRunning: value });
      return;
    }
    
    // 其他状态的处理
    globalState[key] = value;
    uni.setStorageSync(key, value);
    uni.$emit('globalStateChange', { key, value });
  } catch (e) {
    console.error('更新全局状态失败:', e);
  }
};

// 获取全局状态
const getGlobalState = (key) => {
  if (key === 'isRunning') {
    // 每次都从存储中获取最新的运行状态
    const runningState = uni.getStorageSync('plunder_running');
    const manuallyStopped = uni.getStorageSync('plunder_manually_stopped') || false;
    return !manuallyStopped && !!runningState;
  }
  return globalState[key];
};

// 检查是否需要登录
const needAuth = (url) => {
  return authPages.some(page => url.startsWith(page));
};

// 修改登录函数
const login = async (cardKey) => {
  try {
    // 调用现有的登录云函数
    const { result } = await uniCloud.callFunction({
      name: 'loginx',
      data: { code: cardKey }
    });

    if (result && result.success) {
      // 登录成功，保存登录信息
      const loginInfo = {
        token: result.token,
        cardKey,
        loginTime: Date.now()
      };
      
      // 保存到本地存储
      uni.setStorageSync('login_info', loginInfo);
      uni.setStorageSync('isLoggedIn', true);
      
      return {
        success: true,
        token: result.token
      };
    } else {
      return {
        success: false,
        message: result?.message || '登录失败'
      };
    }
  } catch (e) {
    console.error('登录失败:', e);
    return {
      success: false,
      message: '登录失败，请稍后重试'
    };
  }
};

// 修改检查登录状态函数
const checkLogin = () => {
  try {
    return uni.getStorageSync('isLoggedIn') === true;
  } catch (e) {
    console.error('检查登录状态失败:', e);
    return false;
  }
};

// 修改登录页面提示
const getLoginHint = () => {
  return '请输入卡密进行验证';
};

// 修改登出函数
const logout = () => {
  const now = Date.now();
  if (now - lastNavigateTime < NAVIGATE_DEBOUNCE) {
    console.log('页面跳转过于频繁，已忽略');
    return;
  }
  lastNavigateTime = now;
  
  // 清除登录状态，但保留卡密
  clearToken();
  uni.removeStorageSync('login_info');
  uni.removeStorageSync('isLoggedIn');
  
  // 跳转到登录页
  uni.reLaunch({
    url: '/pages/login/index'
  });
};

// 修改路由拦截器
const routeInterceptor = () => {
  const list = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab'];
  
  list.forEach(method => {
    uni.addInterceptor(method, {
      invoke(e) {
        const now = Date.now();
        if (now - lastNavigateTime < NAVIGATE_DEBOUNCE) {
          console.log('页面跳转过于频繁，已忽略');
          return false;
        }
        lastNavigateTime = now;

        // 获取要跳转的页面路径
        const url = e.url.split('?')[0];
        
        // 如果是登录页面，直接允许访问
        if (url === '/pages/login/index') {
          return true;
        }
        
        // 判断是否需要登录权限
        if (needAuth(url)) {
          // 检查登录状态
          if (!checkLogin()) {
            // 未登录，跳转到登录页
            uni.reLaunch({
              url: '/pages/login/index'
            });
            return false;
          }
        }
        return true;
      },
      fail(err) {
        console.log(err);
      }
    });
  });
};

// 初始化全局状态
const initGlobalState = () => {
  // 从存储中加载时间设置
  const savedTimeSettings = uni.getStorageSync('time_settings');
  if (savedTimeSettings) {
    globalState.timeSettings = savedTimeSettings;
  }
  
  // 确保运行状态的一致性
  const runningState = uni.getStorageSync('plunder_running');
  const manuallyStopped = uni.getStorageSync('plunder_manually_stopped') || false;
  
  if (manuallyStopped && runningState) {
    // 如果手动停止但存储中还有运行状态，清除运行状态
    uni.removeStorageSync('plunder_running');
    uni.$emit('globalStateChange', { key: 'isRunning', value: false });
    uni.$emit('running-state-changed', { isRunning: false });
  }
};

export default {
  checkLogin,
  routeInterceptor,
  updateGlobalState,
  getGlobalState,
  initGlobalState,
  login,
  logout,
  getLoginHint,
  setToken,
  getToken,
  clearToken,
  isLoggedIn
}; 